import React, { useState, useEffect } from 'react';
import useStore from '../../components/useStore';
import { Button, Card, Col, Empty, Form, notification, Row, Tooltip } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import store from '../../untils/store';
import dayjs from 'dayjs'; // 引入dayjs处理日期
import request from '../../untils/request';

// 通用请求函数封装
const fetchData = async (url, data, showSuccess = true) => {
  try {
    const result = await request(url, {
      method: "POST",
      mode: 'cors',
      body: data
    });
    if (result.code === 200) {
      if (showSuccess && result.msg) {
        notification.success({ message: result.msg });
      }
      return result;
    } else {
      notification.error({ message: result.msg || "获取数据失败" });
      return null;
    }
  } catch (error) {
    notification.error({ message: "网络请求异常" });
    return null;
  }
};

// 长文本显示组件 - 处理右侧内容
const LongTextDisplay = ({ text, placeholder }) => {
  const displayText = text || placeholder;
  
  return (
    <Tooltip title={displayText} placement="topLeft" mouseEnterDelay={0.3}>
      <div style={styles.contentContainer}>
        {displayText}
      </div>
    </Tooltip>
  );
};

// 标签显示组件 - 处理左侧label，确保完整展示或显示省略号
const LabelDisplay = ({ label }) => (
  <Tooltip title={label} placement="topRight" mouseEnterDelay={0.3}>
    <div style={styles.labelContainer}>
      {label}
    </div>
  </Tooltip>
);

const ShowProductDelivery = () => {
  const { collapsed } = useStore();
  const { localUrl } = store();
  const [form] = Form.useForm();
  const [detail, setDetail] = useState(null);
  const [loading, setLoading] = useState(true);

  // 获取详情数据
  const fetchDetail = async (id) => {
    setLoading(true);
    const result = await fetchData("/admin/productDelivery/getProductDeliveryInfo", { id }, false);
    
    if (result) {
      // 处理日期格式
      const formattedData = {
        ...result.data,
        shipment_date: result.data.shipment_date ? dayjs(result.data.shipment_date).format('YYYY-MM-DD') : null,
        create_time: result.data.create_time ? dayjs(result.data.create_time).format('YYYY-MM-DD HH:mm:ss') : null,
      };
      setDetail(formattedData);
      form.setFieldsValue(formattedData);
    } else {
      setDetail(null);
    }
    
    setLoading(false);
  };

  // 页面加载时获取详情 - 使用hash解析ID
  useEffect(() => {
    // 从hash中获取ID参数
    const hash = window.location.hash.slice(1);
    const queryString = hash.split('?')[1];
    let id = null;
    
    if (queryString) {
      const queryParams = new URLSearchParams(queryString);
      const idStr = queryParams.get('id');
      // 解析为整数
      id = idStr ? parseInt(idStr, 10) : null;
    } 
    
    if (id) {
      fetchDetail(id);
    } else {
      notification.error({ message: "未找到出货单ID参数" });
      console.log("没有找到 id 参数");
      setLoading(false);
    }
  }, []);

  if (loading) {
    return (
      <div style={styles.loadingContainer}>
        <div>加载中...</div>
      </div>
    );
  }

  return (
    <div style={{
      height: "94%",
      backgroundColor: `#F1F1F1`,
      right: "1%",
      top: "4vh",
      overflow: "hidden", // 禁用外层滚动
      width: collapsed ? "94%" : "84%",
      position: "absolute",
      color: "white",
      fontSize: "0.8rem"
    }}>
      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem",
          position: "relative",
          width: "96%",
          marginLeft: "2%",
          display: "flex",
          textIndent: "1rem",
          justifyContent: "flex-start",
          alignContent: "flex-start",
          flexWrap: "wrap"
        }}>
          <Card 
            title="产品出货单详情" 
            style={{ width: "100%", marginTop: "2vh" }}
          >
            {/* 添加带竖向滚动的容器，禁用横向滚动 */}
            <div style={styles.scrollContainer}>
              {detail === null ? (
                <Empty description="未找到产品出货单信息" />
              ) : (
                <Form
                  style={{ width: "95%", maxWidth: 1000, margin: "0 auto" }}
                  form={form}
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                  layout="horizontal"
                >
                  {/* 基础信息区域 - 已移除指定字段 */}
                  {[
                    { label: '出货单号', name: 'shipment_order_id' },
                    { label: '送货地址', name: 'delivery_address' },
                    { label: '出货日期', name: 'shipment_date' },
                    { label: '销售单号', name: 'sales_order_id' },
                    { label: '创建时间', name: 'create_time' },
                  ].map((field) => (
                    <Form.Item
                      key={field.name}
                      name={field.name}
                      label={<LabelDisplay label={field.label} />}
                      style={styles.formItem}
                    >
                      <LongTextDisplay 
                        text={form.getFieldValue(field.name)} 
                        placeholder={`${field.label}为空`} 
                      />
                    </Form.Item>
                  ))}

                  {/* 附件区域说明 */}
                  <div style={{
                    margin: '16px 0 8px',
                    paddingLeft: 'calc(6/24 * 100%)',
                    color: '#666',
                    fontSize: '14px'
                  }}>
                    <span style={{ marginRight: 4 }}>📎</span>
                    附件文件：以下为出货相关凭证文件，可点击下载查看
                  </div>

                  {/* 附件区域 */}
                  <Row gutter={[16, 16]} style={{ paddingLeft: 'calc(6/24 * 100%)' }}>
                    {[
                      { label: '交货清单', name: 'delivery_list', text: '下载交货清单' },
                      { label: '出厂验收报告', name: 'factory_acceptance_report', text: '下载验收报告' },
                      { label: '出货计划', name: 'shipment_plan', text: '下载出货计划' },
                      { label: '产品出货单', name: 'product_shipment_order', text: '下载出货单' },
                      { label: '客户验收报告', name: 'customer_acceptance_report', text: '下载客户报告' },
                    ].map((item) => (
                      <Col span={12} key={item.name}>
                        <Form.Item
                          label={<LabelDisplay label={item.label} />}
                          name={item.name}
                          colon={false}
                          labelCol={{ span: 8 }}
                          wrapperCol={{ span: 16 }}
                          style={styles.formItem}
                        >
                          {detail[item.name] ? (
                            <Button icon={<DownloadOutlined />} size="small">
                              <a
                                href={`${localUrl}${detail[item.name]}`}
                                target="_blank"
                                rel="noopener noreferrer"
                              >
                                {item.text}
                              </a>
                            </Button>
                          ) : (
                            <span style={{ color: '#999' }}>未上传{item.label}</span>
                          )}
                        </Form.Item>
                      </Col>
                    ))}
                  </Row>
                </Form>
              )}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
};

const styles = {
  kshcontainer: {
    width: "98%",
    height: "95%",
    position: "absolute",
    top: "3%",
    left: "1%",
    backgroundColor: "white",
    color: "black",
    borderRadius: "10px",
  },
  loadingContainer: {
    height: "100%",
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    fontSize: "1.2rem",
    color: "#333"
  },
  // 滚动容器样式 - 只允许竖向滚动
  scrollContainer: {
    maxHeight: "calc(95vh - 220px)",
    overflowY: "auto",
    overflowX: "hidden",
    padding: "0 16px 16px",
    boxSizing: "border-box",
  },
  // 表单项目整体样式，控制label和内容的间距
  formItem: {
    marginBottom: 16,
  },
  // 左侧标签容器样式 - 确保完整展示或显示省略号
  labelContainer: {
    width: "100%",
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
    paddingRight: 8,
    fontWeight: 500,
  },
  // 右侧内容容器样式
  contentContainer: {
    width: "100%",
    minHeight: "32px",
    padding: "4px 11px",
    border: "1px solid #d9d9d9",
    borderRadius: "4px",
    backgroundColor: "#f5f5f5",
    color: "rgba(0, 0, 0, 0.65)",
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
    boxSizing: "border-box",
  }
};

export default ShowProductDelivery;
